package com.powernode.controller;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;

/**
 * 文件下载
 */
@Controller
@RequestMapping("download")
public class DownloadController {
    private String rootPath = "D:/upload";
    /**
     * 文件下载的方法
     */
    @RequestMapping("loadImage.action")
    public void download(String path, HttpServletResponse response) throws Exception {
        File file = new File(rootPath, path);//本地磁盘文件
        //使用输入流 将文件读入内存中
        FileInputStream fis = new FileInputStream(file);//找参照物将程序运行的内存当作参照物
        byte[] b = new byte[1024];
        int len = -1;
        ServletOutputStream out = response.getOutputStream();//输出流输出客户端
        //设置响应类型  通知浏览器  不要打开
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        //循环读  循环写
        while ((len=fis.read(b)) != -1) {
            out.write(b,0,len);
            out.flush();
        }
        out.close();
        fis.close();
    }
}
